package com.hnhegui.backend.system.mapper;

import com.hnhegui.backend.system.entity.User;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface UserMapper {

    /**
     * 根据用户名查询用户
     */
    @Select("SELECT * FROM t_user WHERE username = #{username}")
    User findByUsername(@Param("username") String username);

    /**
     * 根据手机号查询用户
     */
    @Select("SELECT * FROM t_user WHERE phone = #{phone}")
    User findByPhone(@Param("phone") String phone);

    /**
     * 根据邮箱查询用户
     */
    @Select("SELECT * FROM t_user WHERE email = #{email}")
    User findByEmail(@Param("email") String email);

    /**
     * 根据用户ID查询用户
     */
    @Select("SELECT * FROM t_user WHERE user_id = #{userId}")
    User findById(@Param("userId") Long userId);

    /**
     * 插入用户
     */
    @Insert("INSERT INTO t_user (username, password, phone, email, role, status, create_time, update_time) " +
            "VALUES (#{username}, #{password}, #{phone}, #{email}, #{role}, #{status}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "userId")
    int insert(User user);

    /**
     * 更新用户
     */
    @Update("UPDATE t_user SET username = #{username}, phone = #{phone}, email = #{email}, " +
            "role = #{role}, status = #{status}, update_time = #{updateTime} WHERE user_id = #{userId}")
    int update(User user);

    /**
     * 批量插入用户
     * 用于大批量数据生成，使用动态SQL拼接多条INSERT语句
     *
     * @param users 用户列表
     * @return 插入成功的记录数
     */
    @InsertProvider(type = UserSqlProvider.class, method = "batchInsert")
    int batchInsert(@Param("users") List<User> users);

    /**
     * 动态查询用户列表（分页）
     */
    @SelectProvider(type = UserSqlProvider.class, method = "searchUsers")
    List<User> searchUsers(
            @Param("username") String username,
            @Param("phone") String phone,
            @Param("status") Integer status,
            @Param("role") String role,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime,
            @Param("offset") Integer offset,
            @Param("limit") Integer limit
    );

    /**
     * 查询符合条件的用户总数
     */
    @SelectProvider(type = UserSqlProvider.class, method = "countUsers")
    Long countUsers(
            @Param("username") String username,
            @Param("phone") String phone,
            @Param("status") Integer status,
            @Param("role") String role,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime
    );
}
